'use strict';
module.exports = {
	/**
	 * XXXnameXXX
	 * @url admin/sendmsg/pub/batch 前端调用的url参数地址
	 * data 请求参数
	 * @param {String} params1  参数1
	 */
	main: async (event) => {
		const db = uniCloud.database();
		var nowtime = new Date().getTime()

		//====从数据库获取token====
		const tokenFromDb = await db.collection('a_config').where({
			name: "kstoken"
		}).get()
		var access_token = tokenFromDb.data[0].token
		var expire_time = tokenFromDb.data[0].expire_time
		//====从数据库获取token结束====

		//====如果token已经过期，则重新获取====
		if (expire_time < nowtime) {
			console.log("重新获取");
			let url = "https://open.kuaishou.com/oauth2/access_token"
			const token = await uniCloud.httpclient.request(url, {
				method: 'POST',
				data: {
					"app_id": "ks668503071139989702",
					"app_secret": "1h3A4WYnxswhYgLjbCJ_oA",
					"grant_type": "client_credentials"
				},
				contentType: 'x-www-form-urlencoded',
				dataType: 'json' // 指定返回值为json格式，自动进行parse
			})
			console.log("token=", token.data.access_token);

			db.collection('a_config').where({
				name: "kstoken"
			}).update({
				token: token.data.access_token,
				expire_time: nowtime + 7000000 //到期时间为当前时间加7000秒
			})
			//过期后重新获取并更新数据库的值
			var access_token = token.data.access_token
		}
		//====重新获取token结束====

		let {
			data = {}, userInfo, util, filterResponse, originalParam
		} = event;
		let {
			customUtil,
			uniID,
			config,
			pubFun,
			vk,
			_
		} = util;
		let {
			uid,
			msgs,
			things
		} = data;
		let res = {
			code: 0,
			msg: ""
		};
		// 业务逻辑开始-----------------------------------------------------------
		console.log("things=", things);
		let batchRunRes = await vk.pubfn.batchRun({
			// 主执行函数
			main: async (item, index) => {
				await vk.pubfn.sleep((Math.floor(Math.random() * (3 - 0)) + 0) * 100);
				console.log("msgType=",item.msgType);
				//====判断消息类型，执行不同函数====
				if (item.msgType == "qdtx") {
					qdtx(access_token, item.openid)
				}
				if (item.msgType == "rbxj") {
					rbxj(access_token, item.openid)
				}
				if (item.msgType == "zjgx") {
					zjgx(access_token, item.openid)
				}
				//====判断消息类型结束====

				//====更改状态为已发送====
				const updtate = await db.collection('a_dingyue').doc(item._id).update({
					is_send: true
				})
				//====更改状态结束====

				return {
					code: 0,
					index
				}
			},
			// 最大并发量，如果设置为1，则会按顺序执行
			concurrency: 100,
			// 数据源，这些数据会依次跑一遍main函数
			data: msgs
		});


		// 业务逻辑结束-----------------------------------------------------------
		return res;

		async function qdtx(mytoken, openid) {
			// 签到提醒
			const pushmsg = {
				"app_id": "ks668503071139989702",
				"access_token": mytoken,
				"template_id": "2eJbbGXI0wGJEzt88Xwks",
				"to_user": openid,
				"page": "/pages/index/index",
				"data": {
					"thing01": {
						"value": "签到名称"
					},
					"thing02": {
						"value": "可领福利"
					},
					"thing03": {
						"value": "温馨提示"
					}
				},
			}
			tosend(pushmsg)
		}

		async function zjgx(mytoken, openid) {
			//剧集更新
			const pushmsg = {
				"app_id": "ks668503071139989702",
				"access_token": mytoken,
				"template_id": "WRuruUjXxXv0wjhZPXbDm",
				"to_user": openid,
				"page": "/pages/index/index",
				"data": {
					"thing01": {
						"value": "剧集标题"
					},
					"number01": {
						"value": 8
					},
					"date01": {
						"value": "2022年7月28号"
					}
				}
			}
			tosend(pushmsg)
		}

		async function rbxj(mytoken, openid) {
			//热播新剧
			const pushmsg = {
				"app_id": "ks668503071139989702",
				"access_token": mytoken,
				"template_id": "F6OJ8H8bGanaWHovkpEK-",
				"to_user": openid,
				"page": "/pages/index/index",
				"data": {
					"thing01": {
						"value": "热播新剧"
					},
					"date01": {
						"value": "2022年7月28号"
					}
				}
			}
			tosend(pushmsg)
		}

		async function tosend(pushmsg) {
			let sendurl = "https://open.kuaishou.com/openapi/mp/developer/message/template/send";
			const send = await uniCloud.httpclient.request(sendurl, {
				method: 'POST',
				data: JSON.stringify(pushmsg),
				contentType: 'x-www-form-urlencoded', 
				dataType: 'json' // 指定返回值为json格式，自动进行parse
			})
			console.log("send=", send);
		}
	}
}
